package com.zhss.demo.concurrent;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁得简单例子
 */
public class ReentractLockDemo {

    static int data = 0;
    // 这里如果传入一个true就使用的是公平锁
    static ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        new Thread(() -> {
            for(int i = 0; i < 10; i++) {
                // 加锁
                lock.lock();
                try {
                    // 加锁一段时间之后放弃
                    boolean b = lock.tryLock(10, TimeUnit.SECONDS);
                    if (b){
                        lock.unlock();
                    } else{
                        System.out.println("加锁失败");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ReentractLockDemo.data++;
                System.out.println(ReentractLockDemo.data);
                LinkedList<String> strings = new LinkedList<>();
                strings.add("1");
                // 释放锁
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            for(int i = 0; i < 10; i++) {
                // 加锁
                lock.lock();
                ReentractLockDemo.data++;
                System.out.println(ReentractLockDemo.data);
                // 释放锁
                lock.unlock();
            }
        }).start();
    }
}
